const {request} = require("../../request/index.js");
const crypto = require("../../utils/test");
const ImageSource = require("../../utils/image_path");
const dataGet = require("../../request/dataGet.js");
const app=getApp()
Page({

    data: {
        NavbarHeight:app.globalData.navBarHeight + app.globalData.statusBarHeight,
        WindowWidth:app.globalData.windowWidth,
        navigationSetting:{
            title:'DIY专区',
            model:1,
        },
        cardsCategory:["生椰拿铁","经典美式","经典拿铁","樱花拿铁","抹茶拿铁","摩卡"],
        cardsData:[],
        // cardsData:[[{"id":8,"cardId":7,"date":"2023-02-04T16:00:00.000+00:00","collect":0,"category":"拿铁咖啡","cardOrder":null,"imageSrc":null},{"id":6,"cardId":8,"date":"2023-01-31T16:00:00.000+00:00","collect":0,"category":"拿铁咖啡","cardOrder":null,"imageSrc":null}],[{"id":1,"cardId":1,"date":"2023-04-04T16:00:00.000+00:00","collect":1,"category":"生椰拿铁","cardOrder":null,"imageSrc":null},{"id":4,"cardId":3,"date":"2023-03-30T16:00:00.000+00:00","collect":1,"category":"生椰拿铁","cardOrder":null,"imageSrc":null},{"id":2,"cardId":2,"date":"2023-02-21T16:00:00.000+00:00","collect":1,"category":"生椰拿铁","cardOrder":null,"imageSrc":null},{"id":9,"cardId":4,"date":"2023-02-09T16:00:00.000+00:00","collect":0,"category":"生椰拿铁","cardOrder":null,"imageSrc":null},{"id":10,"cardId":5,"date":"2023-02-04T16:00:00.000+00:00","collect":0,"category":"生椰拿铁","cardOrder":null,"imageSrc":null},{"id":13,"cardId":6,"date":"2023-02-04T16:00:00.000+00:00","collect":0,"category":"生椰拿铁","cardOrder":null,"imageSrc":null}]],
        category:0,
        groupDataArr:[],
        groupCollectDataArr:[],
        showDate:[],
        pickerDate:[],
        nowDate:app.globalData.nowTime.substring(0,4)+app.globalData.nowTime.substring(5,7),
        arrayYear:[],
        arrayMonth:[],
        arrayMonthThisYear:[],
        YearFlag:1,
        pickerActive:0,
        maskActive:0,
        posScroll:"item0",
        collectFlag:0,
        clickId:0,
        options:"",
    },
    onLoad(options){
        var year=parseInt(this.data.nowDate.substr(0,4))-2015;
        var month=parseInt(this.data.nowDate.substr(4,2))-1;
        this.setData({
            showDate:[month,year],
        })
        this.setData({
            options: options
        })
    },
    async onShow(){
        if(app.globalData.userCardChangeFlag==1){
            await dataGet.getUserCardData();
            app.globalData.userCardChangeFlag=0;
        }
        const data=wx.getStorageSync("userCards");
        this.setData({
            cardsData:data.data,
        });
        this.dealCardsData();
        this.preDealData(this.data.options)
    },
    preDealData(options){
        const title = options.title
        const clickId=options.cardId
        const category=options.category
        this.setData({
            navigationSetting:{
                title:title,
                model:1,
            },
            clickId:clickId,
            category:category
        })
        this.cardDataChange();
        if(clickId!=0){
            this.scrollToCard();
        }
        var res = new Array();
        for(let i=2015; i<=parseInt(this.data.nowDate.substr(0,4));i++){
            res.push(i.toString()+"年");
        }
        this.setData({
            arrayYear:res,
        })
        var res = new Array();
        for(let i=1; i<=12;i++){
            res.push(i.toString()+"月");
        }
        this.setData({
            arrayMonth:res,
        })
        var res = new Array();
        for(let i=1; i<=parseInt(this.data.nowDate.substr(4,2));i++){
            res.push(i.toString()+"月");
        }
        this.setData({
            arrayMonthThisYear:res,
        })
    },
    getCardsData(){
        var that=this;
        setTimeout(()=>{
            let params={
                url:'/userCard',
                method: 'GET',
                data: {
                    openId:app.globalData.openId,
                },
            }
            request(params).then(res=>{
                const data=JSON.parse(crypto.AES_DE(res.data))
                let category = []
                let values=[];
                let categoryAll=["生椰拿铁","经典美式","经典拿铁","樱花拿铁","抹茶拿铁","摩卡"]
                var temp=Object.values(data)
                var fileList=new Array();
                console.log(temp)
                for (let i = 0; i < Object.keys(data).length; i++){
                    for(let j=0;j<temp[i].length;j++){
                        fileList.push(ImageSource.Base+"/icon/roleCard/"+temp[i][j].imageSrc);
                    }
                }
                console.log(fileList)
                new Promise(resolve =>{
                    wx.cloud.getTempFileURL({
                        fileList:fileList,
                        success:res=>{
                            console.log(res);
                            var count=0;
                            for (let i = 0; i < Object.keys(data).length; i++){
                                for(let j=0;j<temp[i].length;j++){
                                    temp[i][j].imageSrc=res.fileList[count++].tempFileURL;
                                }
                            }
                            for (let i = 0; i < Object.keys(data).length; i++){
                                category.push(Object.keys(data)[i]);
                            }
                            categoryAll.forEach(tmp=>{
                                let index=category.indexOf(tmp);
                                console.log(tmp+index)
                                if(index==-1){
                                    values.push([])
                                }
                                else{
                                    values.push(temp[index]);
                                }
                            })
                            console.log(values);
                            resolve();
                        }
                    })
                }).then(()=>{
                    that.setData({
                        cardsCategory:categoryAll,
                        cardsData:values,
                    })
                    wx.setStorageSync("userData",{time:Date.now(),data:that.data.cardsData});
                    console.log(that.data.cardsData)
                    setTimeout(()=>{
                        this.dealCardsData();
                    },200)
                })
            })
        },800)
    },
    dealCardsData(){
        let categoryAll=["生椰拿铁","经典美式","经典拿铁","樱花拿铁","抹茶拿铁","摩卡"]
        let category = []
        let values=[];
        categoryAll.forEach((item,index)=>{
            if(this.data.cardsData[index].length!=0){
                category.push(item);
                values.push(this.data.cardsData[index])
            }
        })
        this.setData({
            cardsCategory:category,
            cardsData:values,
        })
    },
    returnPage(){
        wx.navigateBack({
            delta: 1
        });
    },
    categoryChangeItemTap(e){
        const index=e.currentTarget.dataset.index;
        this.setData({
            category:index,
        })
        this.cardDataChange();
    },
    cardDataChange(){
        let groupData = new Map()
        this.data.cardsData[this.data.category].forEach(item => {
            // 将数据自带的时间字段分割成两段，日期用于分组，时间用于展示
            let date= item.date.substr(0,7);
            if(!groupData.has(date)) {
                groupData.set(date, [item])
            } else {
                groupData.get(date).push(item)
            }
        })
        let groupDataArr = [...groupData.entries()];
        // console.log(groupDataArr);
        this.setData({
                groupDataArr:groupDataArr
            }
        )
        let groupDataCollect = new Map()
        this.data.cardsData[this.data.category].forEach(item => {
                if(item.collect===1){
                    let date= item.date.substr(0,7);
                    if(!groupDataCollect.has(date)) {
                        groupDataCollect.set(date, [item])
                    } else {
                        groupDataCollect.get(date).push(item)
                    }
                }
            }
        )
        let groupDataCollectArr = [...groupDataCollect.entries()];
        this.setData({
                groupCollectDataArr:groupDataCollectArr
            }
        )
    },
    DatePickerItemTap() {
        this.setData({
            pickerActive: 1,
            maskActive: 1,
        })
    },
    scrollToPos() {
        var query = wx.createSelectorQuery();
        query.select('.btn_line').boundingClientRect()
        setTimeout(() => {
                query.exec((res) => {
                    var distance_tmp = res[0].bottom;
                    var query2 = wx.createSelectorQuery();
                    //选择id
                    query2.select('#' + this.data.posScroll).boundingClientRect()
                    setTimeout(() => {
                        query2.exec((resc) => {
                            //res就是 所有标签为mjltest的元素的信息 的数组
                            var top = resc[0].top;
                            var distance = parseFloat(distance_tmp) - 32 - parseFloat(top);
                            setTimeout(() => {
                                wx.pageScrollTo({
                                    scrollTop: -distance,
                                    duration: 0,
                                })
                            }, 100);

                        })
                    }, 100)

                })
            }, 100
        )
    },
    DataCollectPickerItemTap(){
        if(this.data.collectFlag==0){
            this.setData({
                collectFlag:1,
            })
        }else{
            this.setData({
                collectFlag:0,
            })
        }
    },
    ClosePickerItemTap() {
        this.setData({
            pickerActive: 0,
            maskActive: 0,
        })
    },
    ChangeDateItemTap(e) {
        this.setData({
            showDate: this.data.pickerDate,
        })
        this.getDateScroll();
        this.ClosePickerItemTap();

    },
    bindChange(e) {
        // console.log('picker下拉项发生变化后，下标为：', e.detail);
        const month = e.detail.value[0];
        const year = e.detail.value[1];
        // console.log(year);
        // 当前年为2023
        if (year == 8) {
            this.setData({
                YearFlag: 1,
            })
        } else {
            this.setData({
                YearFlag: 0,
            })
        }
        this.setData({
            pickerDate: [month, year],
        })
        // console.log(this.data.pickerDate)
    },
    getDateScroll() {
        let i;
        for (i = 0; i < this.data.groupDataArr.length; i++) {
            var year = parseInt(this.data.groupDataArr[i][0].substring(0, 4));
            var month = parseInt(this.data.groupDataArr[i][0].substring(5, 7));
            if (this.data.showDate[1] + 2015 < year || (this.data.showDate[1] + 2015 == year && this.data.showDate[0] + 1 < month)) {
                continue;
            } else {
                break;
            }
        }
        if (i >= this.data.groupDataArr.length) {
            i--;
        }
        this.setData({
            posScroll: "item" + i,
        })
        console.log(this.data.posScroll);
        this.scrollToPos();
    },
    cardItemTap(e){
        const index=e.currentTarget.dataset.index.id;
        if(index==this.data.clickId){
            this.setData({
                clickId:0
            })
        }
        else{
            this.setData({
                clickId:index
            })
        }
    },
    getResItemTap(){
        var pages = getCurrentPages();   //当前页面
        var prePage = pages[pages.length - 2];   //上个页面
        // 直接给上一个页面赋值
        console.log(this.data.category);
        prePage.setData({
            cardId: this.data.clickId,
            category:this.data.category,
            categoryName:this.data.cardsCategory[this.data.category]
        });
        // }
        wx.navigateBack({
            delta: 1
        })
    },
    scrollToCard(){
        var query = wx.createSelectorQuery();
        query.select('.btn_line').boundingClientRect()
        setTimeout(() => {
                query.exec((res) => {
                    var distance_tmp = res[0].bottom;
                    var query2 = wx.createSelectorQuery();
                    //选择id
                    query2.select('#card' + this.data.clickId).boundingClientRect()
                    setTimeout(() => {
                        query2.exec((resc) => {
                            //res就是 所有标签为mjltest的元素的信息 的数组
                            var top = resc[0].top;
                            var distance = parseFloat(distance_tmp) +70 - parseFloat(top);
                            setTimeout(() => {
                                wx.pageScrollTo({
                                    scrollTop: -distance,
                                    duration: 0,
                                })
                            }, 100);

                        })
                    }, 100)

                })
            }, 100
        )
    },
})